/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {baseUrl} from '@/config/env';
import {Base64} from 'js-base64'
import website from '@/config/website'
import {getToken} from '@/util/auth'
import {serialize} from '@/util/util'
import store from '@/store/'
import router from '@/router/router'
import {Message} from 'element-ui'

//请求超时时间
axios.defaults.timeout = 10000;
//返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500;
};

//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

axios.defaults.baseURL = baseUrl;

// 页面跳转时出现在浏览器顶部的进度条
NProgress.configure({
  //进度环显示隐藏
  showSpinner: false
});

//HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start();
  const meta = (config.meta || {});
  config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  if (getToken() || store.getters.token) {
    config.headers['Dgov-Auth'] = 'Bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
  }
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  return config
}, error => {
  return Promise.reject(error)
});

//HTTPresponse拦截
axios.interceptors.response.use(response => {
  NProgress.done();
  const res = response.data
  if (response.status === 200) {
    return res
  }
  //如果在白名单里则自行catch逻辑处理
  const statusWhiteList = website.statusWhiteList || [];
  if (statusWhiteList.includes(response.status)) return Promise.reject(response);

  if (response.status === 401) {
    store.dispatch('logout').then(() => router.push({path: '/login'}));
  } else if (response.status === 403) {
    Message({
      message: '抱歉，您无权访问！',
      type: 'error',
      duration: 5 * 1000
    })
  } else {
    Message({
      message: res.msg || 'Error 未知错误',
      type: 'error',
      duration: 5 * 1000
    })
  }
  return Promise.reject(new Error(res.msg || 'Error'))
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
})

export default axios;
